package com.fadis.server;

import com.fadis.cmd.CmdDispatcher;
import com.fadis.expire.ExpireMgmr;
import com.fadis.persist.AOFMgmr;
import com.fadis.persist.FileLogProvider;
import com.fadis.utils.SafeEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.util.concurrent.*;

public class FadisServer {

    private static final ExecutorService acceptThread = Executors.newSingleThreadExecutor();

    public static void init(String aofFilePath){
        ExpireMgmr.startClearExpiredKeys();
        AOFMgmr.setAOFLogProvider(new FileLogProvider(aofFilePath));
        AOFMgmr.restoreFromLog();
    }

    public static void start(int port){
        acceptThread.submit(new Runnable() {
            @Override
            public void run() {
                FadisServer server = new FadisServer();
                server.startServer(port);
            }
        });
    }


    private  void startServer(int port) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            serverBootstrap.group(group);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline p = socketChannel.pipeline();
                    p.addLast(new CmdHandler());
//                    p.addLast(new RedisDecoder());
//                    p.addLast(new RedisBulkStringAggregator());
//                    p.addLast(new RedisArrayAggregator());
//                    p.addLast(new RedisEncoder());
//                    p.addLast(new NettyServerHandler());
                }
            });
            serverBootstrap.channel(NioServerSocketChannel.class);
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("Fadis server 启动成功！");
            channelFuture.channel().closeFuture().sync();

        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            group.shutdownGracefully();
        }
    }



}
